<template>
  <div class="main">
    <el-button type="primary" @click="$router.go(-1)" icon="el-icon-back">返回上级</el-button>
    <div v-for="item in resumeForm" :key="item.value">
      <template v-if="'type' in item && item.type == 'list'">
        <el-form
          v-for="(lItem, index) in resumeData[item.value]"
          :model="resumeData[item.value][index]"
          :key="`resumeData.${item.value}.${index}`"
          class="form-list"
          :ref="`resumeData.${item.value}.${index}`">
          <h4 class="title">{{ `${item.title}${index + 1}` }}</h4>
          <el-form-item
            label-width="15%"
            v-for="cItem in item.children"
            :prop="cItem.value"
            :rules="cItem.rules"
            :key="cItem.value"
            :label="cItem.label">
            <el-select
              clearable
              v-if="cItem.type == 'select'"
              v-model="resumeData[item.value][index][cItem.value]"
              :placeholder="`请选择${cItem.label}`">
              <el-option v-for="oItem in cItem.options" :key="oItem.value" :label="oItem.label" :value="oItem.value"></el-option>
            </el-select>
            <el-input-number
              v-else-if="cItem.type == 'number'"
              v-model="resumeData[item.value][index][cItem.value]"
              :min="cItem.min"
              :max="cItem.max"></el-input-number>
            <el-date-picker
              v-else-if="cItem.type == 'date'"
              v-model="resumeData[item.value][index][cItem.value]"
              type="date"
              format="yyyy 年 MM 月 dd 日"
              value-format="yyyy-MM-dd"
              :placeholder="`请选择${cItem.label}`">
            </el-date-picker>
            <el-input
              v-else
              :type="'type' in cItem ? cItem.type : 'text'"
              autosize
              clearable
              :show-word-limit="'type' in cItem && cItem.type == 'textarea'"
              v-model="resumeData[item.value][index][cItem.value]"
              :maxlength="'maxLength' in cItem ? cItem.maxLength : ''"
              :placeholder="`请输入${cItem.label}`"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="text" class="deleteForm" icon="el-icon-delete" @click="deleteForm(item.value, index, item.title)"
              >删除{{ item.title }}</el-button
            >
          </el-form-item>
        </el-form>
        <el-button class="addForm" type="text" icon="el-icon-plus" @click="addForm(item.value)">添加{{ item.title }}</el-button>
      </template>
      <el-form v-else :model="resumeData[item.value]" :key="`resumeData.${item.value}`" class="form-list" :ref="`resumeData.${item.value}`">
        <h4 class="title">{{ `${item.title}` }}</h4>
        <el-form-item
          label-width="15%"
          v-for="cItem in item.children"
          :rules="cItem.rules"
          :prop="cItem.value"
          :key="cItem.value"
          :label="cItem.label">
          <el-select clearable v-if="cItem.type == 'select'" v-model="resumeData[item.value][cItem.value]" :placeholder="`请选择${cItem.label}`">
            <el-option v-for="oItem in cItem.options" :key="oItem.value" :label="oItem.label" :value="oItem.value"></el-option>
          </el-select>
          <el-input-number
            v-else-if="cItem.type == 'number'"
            v-model="resumeData[item.value][cItem.value]"
            :min="cItem.min"
            :max="cItem.max"></el-input-number>
          <el-date-picker
            v-else-if="cItem.type == 'date'"
            v-model="resumeData[item.value][cItem.value]"
            type="date"
            format="yyyy 年 MM 月 dd 日"
            value-format="yyyy-MM-dd"
            :placeholder="`请选择${cItem.label}`">
          </el-date-picker>
          <!-- 上传附件 -->
          <el-upload
            v-else-if="cItem.type == 'file'"
            action="#"
            :limit="1"
            :on-progress="
              (event, file, fileList) => {
                return uploadResume(event, file, fileList, cItem.value)
              }
            "
            :on-change="resumeChange"
            :accept="cItem.accept"
            auto-upload
            show-file-list>
            <el-button type="primary" icon="el-icon-upload2">上传附件</el-button>
          </el-upload>
          <el-input
            v-else
            :type="'type' in cItem ? cItem.type : 'text'"
            autosize
            clearable
            :show-word-limit="'type' in cItem && cItem.type == 'textarea'"
            v-model="resumeData[item.value][cItem.value]"
            :maxlength="'maxLength' in cItem ? cItem.maxLength : ''"
            :placeholder="`请输入${cItem.label}`"></el-input>
        </el-form-item>
      </el-form>
    </div>
    <el-button type="primary" class="submit" @click="submitForm(resumeData)">提交</el-button>
  </div>
</template>

<script>
import { validPhone, validEmail, validIdCard } from '@/utils/validate'
import { mapGetters } from 'vuex'
import { downloadFileStream } from '@/utils/file'
export default {
  computed: {
    ...mapGetters(['id']),
    currentId() {
      return this.$route.query.id
    },
    formType() {
      return this.$route.query.type
    },
  },
  data() {
    const validatePhone = (rule, value, callback) => {
      if (!validPhone(value)) {
        callback(new Error('手机号格式不正确!'))
      } else {
        callback()
      }
    }
    const validDataEmail = (rule, value, callback) => {
      if (!validEmail(value)) {
        callback(new Error('邮箱格式不正确!'))
      } else {
        callback()
      }
    }

    const validDataIdCard = (rule, value, callback) => {
      if (!validIdCard(value)) {
        callback(new Error('身份证格式不正确!'))
      } else {
        callback()
      }
    }
    return {
      resumeData: {
        resume: {},
        workExperiences: [],
        educationExperiences: [],
        projectExperiences: [],
      },
      resumeForm: [
        {
          title: '基本信息',
          value: 'resume',
          children: [
            {
              label: '简历名',
              value: 'name',
              rules: [
                {
                  required: true,
                  message: '请输入简历名称',
                  trigger: 'blur',
                },
              ],
            },
            {
              label: '姓名',
              value: 'username',
              rules: [
                {
                  required: true,
                  message: '请输入姓名',
                  trigger: 'blur',
                },
              ],
            },
            {
              label: '头像',
              value: 'avatar',
              type: 'file',
              accept: '.png,.jpg,.jpeg,.gif',
            },
            {
              label: '性别',
              value: 'sex',
              type: 'select',
              options: [
                {
                  label: '女',
                  value: 0,
                },
                {
                  label: '男',
                  value: 1,
                },
              ],
              rules: [
                {
                  required: true,
                  message: '请选择性别',
                  trigger: 'change',
                },
              ],
            },
            {
              label: '年龄',
              value: 'age',
              type: 'number',
              min: 18,
              max: 60,
              rules: [
                {
                  required: true,
                  message: '请输入年龄',
                  trigger: 'blur',
                },
                {
                  type: 'number',
                  min: 18,
                  max: 60,
                  message: '年龄在18-60之间',
                },
              ],
            },
            {
              label: '生日',
              value: 'birthday',
              type: 'date',
              rules: [
                {
                  required: true,
                  message: '请选择生日',
                  trigger: 'change',
                },
              ],
            },
            {
              label: '手机号',
              value: 'phone',
              rules: [
                {
                  validator: validatePhone,
                  trigger: 'blur',
                },
                {
                  required: true,
                  message: '请输入手机号',
                  trigger: 'blur',
                },
              ],
            },
            {
              label: '邮箱',
              value: 'email',
              rules: [
                {
                  validator: validDataEmail,
                  trigger: 'blur',
                },
                {
                  required: true,
                  message: '请输入邮箱',
                  trigger: 'blur',
                },
              ],
            },
            {
              label: '住址',
              value: 'address',
              type: 'textarea',
              rules: [
                {
                  required: true,
                  message: '请输入住址',
                  trigger: 'blur',
                },
              ],
            },
            {
              label: '身份证号',
              value: 'identity',
              rules: [
                {
                  required: true,
                  message: '请输入身份证号',
                  trigger: 'blur',
                },
                {
                  validator: validDataIdCard,
                  trigger: 'blur',
                },
              ],
            },
            {
              label: '专业技能',
              value: 'skill',
              type: 'textarea',
              maxLength: 500,
              rules: [
                {
                  required: true,
                  message: '请输入专业技能',
                  trigger: 'blur',
                },
              ],
            },
            {
              label: '自我评价',
              value: 'advantage',
              type: 'textarea',
              maxLength: 500,
              rules: [
                {
                  required: true,
                  message: '请输入自我评价',
                  trigger: 'blur',
                },
              ],
            },
            {
              label: '附件',
              value: 'advantage',
              type: 'file',
              accept: '.pdf,.doc,.docx',
            },
          ],
        },

        {
          title: '教育经历',
          value: 'educationExperiences',
          type: 'list',
          column: 2,
          children: [
            {
              label: '开始时间',
              value: 'start',
              type: 'date',
              rules: [
                {
                  required: true,
                  message: '请选择开始时间',
                  trigger: 'change',
                },
              ],
            },
            {
              label: '结束时间',
              value: 'end',
              type: 'date',
              rules: [
                {
                  required: true,
                  message: '请选择结束时间',
                  trigger: 'change',
                },
              ],
            },
            {
              label: '学校',
              value: 'school',
              rules: [
                {
                  required: true,
                  message: '请输入学校',
                  trigger: 'blur',
                },
              ],
            },
            {
              label: '专业',
              value: 'major',
              rules: [
                {
                  required: true,
                  message: '请输入专业',
                  trigger: 'blur',
                },
              ],
            },
            {
              label: '学历',
              value: 'degreeName',
              type: 'select',
              options: [
                {
                  label: '中专',
                  value: 0,
                },
                {
                  label: '大专',
                  value: 1,
                },
                {
                  label: '本科',
                  value: 2,
                },
                {
                  label: '研究生及以上',
                  value: 3,
                },
              ],
              rules: [
                {
                  required: true,
                  message: '请选择学历',
                  trigger: 'change',
                },
              ],
            },
          ],
        },
        {
          title: '工作经历',
          value: 'workExperiences',
          type: 'list',
          column: 2,
          children: [
            {
              label: '开始时间',
              value: 'start',
              type: 'date',
              rules: [
                {
                  required: true,
                  message: '请选择开始时间',
                  trigger: 'change',
                },
              ],
            },
            {
              label: '结束时间',
              value: 'end',
              type: 'date',
              rules: [
                {
                  required: true,
                  message: '请选择结束时间',
                  trigger: 'change',
                },
              ],
            },
            {
              label: '公司名称',
              value: 'company',
              rules: [
                {
                  required: true,
                  message: '请输入公司名称',
                  trigger: 'blur',
                },
              ],
            },
            {
              label: '岗位职责',
              value: 'duty',
              type: 'textarea',
              maxLength: 500,
              rules: [
                {
                  required: true,
                  message: '请输入岗位职责',
                  trigger: 'blur',
                },
              ],
            },
          ],
        },
        {
          title: '项目经历',
          value: 'projectExperiences',
          type: 'list',
          column: 2,
          children: [
            {
              label: '开始时间',
              value: 'start',
              type: 'date',
              rules: [
                {
                  required: true,
                  message: '请选择开始时间',
                  trigger: 'change',
                },
              ],
            },
            {
              label: '结束时间',
              value: 'end',
              type: 'date',
              rules: [
                {
                  required: true,
                  message: '请选择结束时间',
                  trigger: 'change',
                },
              ],
            },
            {
              label: '项目名称',
              value: 'name',
              rules: [
                {
                  required: true,
                  message: '请输入项目名称',
                  trigger: 'blur',
                },
              ],
            },
            {
              label: '项目角色',
              value: 'role',
              rules: [
                {
                  required: true,
                  message: '请输入项目角色',
                  trigger: 'blur',
                },
              ],
            },
            {
              label: '项目描述',
              value: 'description',
              type: 'textarea',
              maxLength: 500,
              rules: [
                {
                  required: true,
                  message: '请输入项目描述',
                  trigger: 'blur',
                },
              ],
            },
          ],
        },
      ],
      addressTree: [],
    }
  },
  created() {
    this.getChinaDistrict()
    this.getResume(this.currentId)
  },
  methods: {
    downloadFileStream,
    // 获取简历
    getResume(id) {
      if (this.formType === 'add') {
        return
      }
      this.$store.dispatch('resume/lookOneResume', id).then((response) => {
        this.resumeData = response.data
      })
    },
    // 获取中国省市区
    getChinaDistrict() {
      this.$store.dispatch('map/getChinaDistrict').then((response) => {
        this.addressTree = response
      })
    },
    // 添加简历
    addForm(value) {
      this.resumeData[value].push({})
    },
    // 上传文件
    uploadResume(event, file, fileList, value) {
      if (file == null) {
        return
      }
      this.$store.dispatch('file/uploadFile', file).then((response) => {
        if (response.success) {
          this.resumeData.resume[value] = response.data
        }
      })
    },
    // 删除简历
    deleteForm(value, index, title) {
      if (this.resumeData[value].length == 1) {
        this.$message({
          message: `至少保留一条${title}`,
          type: 'warning',
          showClose: true,
        })
        return
      }
      this.resumeData[value].splice(index, 1)
    },
    checkForms(name) {
      var data = this.resumeData
      var obj = data[name]
      if (obj instanceof Array) {
        for (var i = 0; i < obj.length; i++) {
          this.checkForms(`${name}.${i}`)
          return
        }
      }
      console.log(obj, `校验:resumeData.${name}`, this.$refs[`resumeData.${name}`])
      return new Promise((resolve, reject) => {
        this.$refs[`resumeData.${name}`][0].validate((valid) => {
          if (!valid) {
            reject(false)
          }
          resolve()
        })
      })
    },
    submitForm() {
      var list = []
      list.push(
        this.checkForms('resume'),
        this.checkForms('workExperiences'),
        this.checkForms('educationExperiences'),
        this.checkForms('projectExperiences'),
      )
      Promise.all(list)
        .then(() => {
          this.resumeData.resume.userId = this.id
          this.$store.dispatch('resume/addOneResume', this.resumeData).then((response) => {
            if (response.success) {
              this.$message({
                message: `${type === 'edit' ? '修改' : '添加'}成功`,
                type: 'success',
                showClose: true,
              })
            }
          })
          this.$router.push({
            path: '/resumeList',
          })
        })
        .catch((v) => {
          console.log(v)
          return false
        })
    },
  },
}
</script>

<style lang="scss" scoped>
.main {
  margin-top: 70px;
  border: 1px solid white;
  width: 80%;
  margin-left: 10%;
  height: 83vh;
  overflow: auto;
  .title {
    text-align: center;
  }
  .form-list {
    border: 1px solid white;
  }
  .addForm {
    margin-left: 15%;
  }

  .el-form {
    .el-form-item {
      width: 50%;
      margin-left: 15%;
      ::v-deep .el-input__inner,
      ::v-deep .el-textarea__inner {
        border: 1px solid gray;
      }
    }
  }
  .submit {
    width: 10%;
    margin-left: 45%;
  }
}
</style>
